package com.mall.controller

import com.mall.entity.Product
import com.mall.service.ProductService
import com.mall.util.ResponseUtil
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.web.bind.annotation.*

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/api/product")
@Tag(name = "商品管理", description = "商品相关接口")
class ProductController(private val productService: ProductService) {

    @PostMapping("")
    @Operation(summary = "创建商品", description = "创建一个新的商品")
    fun create(@RequestBody product: Product): ResponseUtil<*> {
        return try {
            productService.create(product)
            ResponseUtil.success("创建成功", product)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "创建失败")
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取商品详情", description = "根据ID获取商品详细信息")
    fun getById(@PathVariable id: Long): ResponseUtil<*> {
        return try {
            val product = productService.getById(id)
            ResponseUtil.success(product)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "获取商品详情失败")
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新商品", description = "更新指定商品的信息")
    fun update(@PathVariable id: Long, @RequestBody product: Product): ResponseUtil<*> {
        return try {
            product.id = id
            productService.update(product)
            ResponseUtil.success("更新成功", null)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "更新失败")
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除商品", description = "根据ID删除商品")
    fun delete(@PathVariable id: Long): ResponseUtil<*> {
        return try {
            productService.delete(id)
            ResponseUtil.success("删除成功", null)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "删除失败")
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取商品列表", description = "分页获取商品列表")
    fun list(
        @RequestParam(defaultValue = "1") page: Int,
        @RequestParam(defaultValue = "10") pageSize: Int
    ): ResponseUtil<*> {
        return try {
            val result = productService.list(page, pageSize)
            ResponseUtil.success(result)
        } catch (e: Exception) {
            ResponseUtil.error<Any?>(e.message ?: "获取列表失败")
        }
    }
}